
package com.probiz.estore.content.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.content.UploadFileFilter;
import com.probiz.estore.common.util.FileUtil;
import com.probiz.estore.content.service.UploadManager;
import com.probiz.estore.core.util.ImageProcessor;
import com.probiz.estore.webapp.action.ImageConf;


public class UploadManagerImpl implements UploadManager 
{

	private Map<String, List<ImageConf>>	categoryImageConfs;

	private ImageProcessor					imageProcessor;

	private boolean							keepOriginalImage	= false;
	
	private List 							categoryProcess;
	

	public void setCategoryProcess(List categoryProcess) {
		this.categoryProcess = categoryProcess;
	}

	/*
	 * 处理图片
	 * 
	 */
	public void processImage(File pfile, String uploadCategory)
			throws IOException {

		String filePath = pfile.getAbsolutePath();
		String fileName = pfile.getName();
		int idx = fileName.lastIndexOf(".");
		String suffix = null;
		if (idx > 0 && idx != fileName.length()) {
			suffix = fileName.substring(idx + 1, fileName.length())
					.toLowerCase();
		}
		List<ImageConf> catagoryImageConfs = getImageConf(uploadCategory,
				suffix);
		if (catagoryImageConfs != null && catagoryImageConfs.size() > 0) {
			for (Iterator<ImageConf> iter2 = catagoryImageConfs.iterator(); iter2
					.hasNext();) {
				ImageConf conf = iter2.next();
				String destFile = appendSuffix(filePath, conf.getSuffix());
				if (conf.isAutoScaleImage()) {
					imageProcessor.scaleImage(filePath, destFile, conf
							.getWidth(), conf.getHeight(), conf.getPadding());
				}
				if (conf.isAutoWatermark()) {
					imageProcessor.addWatermark(destFile, destFile);
				}
			}
			if (!keepOriginalImage) {
				pfile.delete();
			}
		}

	}
	
	//获取列表后缀
	public String[] getSuffixByCategory(String category,String suffix){
		String[] returnArry = null;
		List<ImageConf> catagoryImageConfs = getImageConf(category,
				suffix);
		if (catagoryImageConfs != null && catagoryImageConfs.size() > 0) {
				returnArry = new String[catagoryImageConfs.size()];
			for (int i = 0;i<catagoryImageConfs.size();i++) {
				ImageConf conf = catagoryImageConfs.get(i);
				returnArry[i] = conf.getSuffix();
				
			}
		
		}
		return returnArry;
		
	}
	
	private void listFiles(File file,UploadFileFilter uploadFileFilter,String uploadCatory) throws IOException 
	{
		if (file.isDirectory()) 
		{
			File[] subFiles = file.listFiles(uploadFileFilter);
			for (int i = 0; i < subFiles.length; i++) {
				File subFile = subFiles[i];
				listFiles(subFile,uploadFileFilter,uploadCatory);
			}
		}
		else
		{
			processImage(file, uploadCatory);
		}
		
	}
	
	public void processImageBatchJob() throws IOException{
		
		String uploadPath=ConfigUtil.getInstance().getMediaUploadPath();
		if(this.categoryProcess!=null && this.categoryProcess.size()>0){
			for(Object category:this.categoryProcess){
				String categoryPath = uploadPath+"/"+(String)category;
				File file = new File(categoryPath);
				
				UploadFileFilter uploadFileFilter = new UploadFileFilter(getSuffixByCategory((String)category, "jpg"));
				this.listFiles(file,uploadFileFilter,(String)category);
				
			}
		}
		
	}
	

	/**
	 * 设置图片处理的配置列表，使用ImageConf，一个类别（如product）可配置多次处理。
	 * 
	 * @param imageConfs
	 */
	public void setImageConfs(List<ImageConf> imageConfs) {
		categoryImageConfs = new HashMap<String, List<ImageConf>>();
		for (Iterator<ImageConf> iter = imageConfs.iterator(); iter.hasNext();) {
			ImageConf conf = iter.next();
			List<ImageConf> categoryConfs = categoryImageConfs.get(conf
					.getCategory());
			if (categoryConfs == null) {
				categoryConfs = new ArrayList<ImageConf>();
			}
			categoryConfs.add(conf);
			categoryImageConfs.put(conf.getCategory(), categoryConfs);
		}
	}

	protected String appendSuffix(String srcUrl, String suffix2) {
		StringBuilder sb = new StringBuilder(srcUrl);
		sb.insert(sb.lastIndexOf("."), suffix2);
		return sb.toString();
	}

	protected List<ImageConf> getImageConf(String category, String suffix) {
		if ("jpg".equals(suffix)) {
			return categoryImageConfs.get(category);
		}
		return null;
	}
	
	public List<String> getImageUrls(String imageUrl){
		if(StringUtils.isEmpty(imageUrl)){
			return null;
		}
		List<String> results=new ArrayList<String>();
		results.add(imageUrl);
		List<ImageConf> imageConfigs=null;
		Set<String> categorys=categoryImageConfs.keySet();
		for (String category : categorys) {
			if(imageUrl.indexOf("/"+category+"/")>-1){
				imageConfigs=categoryImageConfs.get(category);
				break;
			}
		}
		if(imageConfigs!=null){
			for (ImageConf imageConf : imageConfigs) {
				String tempImageUrl = appendSuffix(imageUrl, imageConf.getSuffix());
				results.add(tempImageUrl);
			}
		}
		return results;
	}

	public void setImageProcessor(ImageProcessor imageProcessor) {
		this.imageProcessor = imageProcessor;
	}

	/**
	 * 对于需要转换的文件（图片），是否保留原文件。缺省false。
	 * 
	 * @param keepOriginalImage
	 */
	public void setKeepOriginalImage(boolean keepOriginalImage) {
		this.keepOriginalImage = keepOriginalImage;
	}

	
	public List<String> deleteImage(String imageUrl) {
		if(StringUtils.isEmpty(imageUrl)){
			return null;
		}
		List<String> imagePaths=getImageUrls(imageUrl);
		String path = ConfigUtil.getInstance().getMediaUploadPath();
		String realFilePath = path != null && (!path.endsWith("/")) ? path+ "/": path;
		for (String imagePath : imagePaths) {
			FileUtil.delFile(realFilePath + imagePath);
		}
		return null;
	}
}
